/**
 * @file filter
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import * as pick from 'lodash/pick';
import * as assign from 'lodash/assign';
import {Renderer} from '../../../renderer';
import {DropdownButton, MenuItem} from 'react-bootstrap';
import * as cx from 'classnames';
import './col-control.scss';

@Renderer({
  name: 'table-control-col-control',
  desc: 'table控制col展示的小工具',
  test: (path, config) => /(?:^|\/)table\/tool$/.test(path) && ~['columnsToggle'].indexOf(config.type)
})
export default class ControlCol extends PureComponent {
  static propTypes = {

    // 渲染哪些col
    cols: PropTypes.array,

    // 当改变的时候,触发的事件
    onColsChange: PropTypes.func,

    title: PropTypes.string
  };

  static defaultProps = {
    cols: [],
    title: '列控制'
  };

  constructor(props) {
    super(props);
    let checkMap = {};

    // 将cols map一下
    let cols = props.cols.map(item => {
      return assign({}, item, {toggled: item.toggled === undefined ? true : item.toggled});
    });

    // 没有选择的
    let checkedLength = 0;
    cols.forEach((item, index) => {
      if (item.toggled !== false && item.label) {
        checkedLength++;
      }
    });

    this.state = {
      cols: cols,
      opened: false,
      checkedLength
    };

    this.changeValue = this.changeValue.bind(this);
    this.toggleList = this.toggleList.bind(this);
    this.hideList = this.hideList.bind(this);
  }

  hideList() {
    this.setState({
      opened: false
    });
  }

  componentWillReceiveProps(nextProps) {
    const {cols} = nextProps;
    let checkedLength = 0;

    let newCols = cols.map(item => {
      return assign({}, item, {toggled: item.toggled === undefined ? true : item.toggled});
    });
    cols.forEach((item, index) => {
      if (item.toggled !== false && item.label) {
        checkedLength++;
      }
    });
    this.setState({
      cols: newCols,
      checkedLength: checkedLength
    });
  }

  componentDidMount() {
    document.addEventListener('click', this.hideList);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.hideList);
  }

  changeValue(index, checked) {
    let {cols, checkedLength} = this.state;
    let {onColsChange} = this.props;
    let newCols = cols.concat();
    newCols[index].toggled = checked;

    onColsChange && onColsChange(newCols);
  }

  renderCheckBox() {

    const {
      cols,
      checkedLength
    } = this.state;
    let body = [];
    cols.forEach((option, index) => {
      if (option.label) {
        body.push(
          <li key={`checkbox-${index}`}>
            <label className="i-checks col-control-label">
                <input
                  type='checkbox'
                  checked={!!option['toggled']}
                  onChange={(e => this.changeValue(index, e.currentTarget.checked))}
                  disabled={!!option['toggled'] && checkedLength == 1}
                />
                <i />
                {option.label}
            </label>
          </li>
        );
      }
    });
    return body;
  }

  toggleList(e) {
    const {opened} = this.state;

    this.setState({
      opened: !opened
    })
  }

  stopPropagation(e) {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
  }

  render() {
    const {
      title
    } = this.props;

    const {
      opened
    } = this.state;

    return (
      <div className={cx('keep-open','btn-group', 'col-control-ul', {open: opened})} title="Columns" onClick={this.stopPropagation}>
        <button type="button" className="btn btn-default dropdown-toggle btn-sm" onClick={this.toggleList}>
          <i className="glyphicon glyphicon-th icon-th"></i>
          <span className="caret"></span>
        </button>
        <ul className="dropdown-menu">
          {this.renderCheckBox()}
        </ul>
      </div>
    );
  }
}
